package com.example.demo.service.Impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.Tool;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author luolinila
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;

    //搜索用户
    @Override
    public User getUserById(int uid) {
        return userMapper.selectByUid(uid);
    }

    //发送邮箱验证码
    @Override
    public String sendEmail(String email) {
        //发件人默认为 QQ 邮箱
        String sender = "3167296902@qq.com";
        String authorizationCode = "zwbqhgwwbvaddhdg";
        if(email.contains("@163.com")) {
            //使用网易邮箱
            sender = "15678093650@163.com";
            authorizationCode = "KFkWMxbPtSY2Z5q9";
        }
        //获取 6 为验证码
        String text = String.valueOf(Tool.randomInt(6));
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.ssl.enable", "true");

            if(email.contains("qq.com")) {
                props.put("mail.smtp.host", "smtp.qq.com");
            }else if(email.contains("163.com")) {
                props.put("mail.smtp.host", "smtp.163.com");
            }

            // 发件人的账号
            props.put("mail.user", sender);
            //发件人的密码
            props.put("mail.password", authorizationCode);

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator auth = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(props.getProperty("mail.user"), props.getProperty("mail.password"));
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, auth);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(email);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject("验证码");

            // 设置邮件的内容体
            message.setContent(text, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            redisTemplate.opsForValue().set("email_" + email, text, 3, TimeUnit.MINUTES);
            return text;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    //注册
    @Override
    public int enroll(String username, String password, String email, String statue) {
        //校验邮箱是否重复
        User user = userMapper.selectByEmail(email);
        if(user != null) {
            return -1;
        }
        //检验验证码是否过期或错误
        String authorizationCode = (String) redisTemplate.opsForValue().get("email_" + email);
        if(authorizationCode == null || !authorizationCode.equals(statue)) {
            return -2;
        }
        redisTemplate.delete("email_" + email);
        //8 位uid
        int uid = Tool.randomInt(8);
        while (userMapper.selectByUid(uid) != null) {
            uid = Tool.randomInt(8);
        }
        //12 位账号
        String account = Tool.randomString(12);
        while (userMapper.selectByAccount(account) != null) {
            account = Tool.randomString(12);
        }
        //存储 RSA 加密之后的密码
        password = Tool.passwordRSA(password);
        user = new User(uid, account, password, username, email);
        userMapper.insert(user);
        return uid;
    }

    //使用邮箱验证码登录
    @Override
    public User loginByEmailCode(String email, String code) {
        if (!Objects.equals(code, redisTemplate.opsForValue().get("email_" + email))) {
            return null;
        }
        redisTemplate.delete("email_" + email);
        return userMapper.selectByEmail(email);
    }

    //使用邮箱密码登录
    @Override
    public User loginByEmailPassword(String email, String password) {
        //RAS 加密后密文校验
        password = Tool.passwordRSA(password);
        User user = userMapper.selectByEmail(email);
        if(user == null || !password.equals(user.getPassword())) {
            return null;
        }
        return user;
    }

    //使用账号密码登录
    @Override
    public User loginByAccountPassword(String account, String password) {
        password = Tool.passwordRSA(password);
        User user = userMapper.selectByAccount(account);
        if(user == null || !password.equals(user.getPassword())) {
            return null;
        }
        return user;
    }
}
